package leecode.链表;

import util.ListNode;

/**
 * @author wangxi created on 2023/5/8 23:57
 * @version v1.0
 *
 * 判断链表是否有环
 *
 * https://leetcode.cn/problems/linked-list-cycle/
 *
 * https://leetcode.cn/problems/linked-list-cycle-ii/
 */
public class HasCycle {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        // 这里是相遇问题，需要从同一节点出发，判定才会准。如果不处于同一点出发,也可以成功，
        // 但是判定一些题会存在超时...
        ListNode slow = head;
        ListNode fast = head;
        while (slow != null && fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                return true;
            }
        }
        return false;
    }
}
